package com.softer.wxzj.common.error;

import com.softer.wxzj.common.enums.MessageEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 异常处理
 *
 * @author Gong Zhiyang
 * @date 2019/4/16
 */
@Slf4j
@ControllerAdvice
public class ExceptionHandle {
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public Map<String, Object> handle(Exception e) {
        //记录错误日志
        log.error("错误信息:()", e.getMessage(), e);
        Map<String, Object> map = new HashMap(6);
        //抛出自定义异常处理
        if (e instanceof CourseException) {
            CourseException courseException = (CourseException) e;
            map.put("data", courseException.getData());
            map.put("message", courseException.getMessage());
            return map;
        }
        if (e instanceof UnauthorizedException) {
            map.put("data", "201");
            map.put("message", "用户没有访问权限");
            return map;
        }
        if (e.getMessage().contains("Data too long")) {
            map.put("data", "201");
            map.put("message", "数据长度超限");
            return map;
        }
        if (e instanceof DataIntegrityViolationException) {
            map.put("data", "201");
            map.put("message", "不允许操作，请检查关联数据！");
            return map;
        }
        //校验失败返回
        if (e instanceof ConstraintViolationException) {
            ConstraintViolationException exs = (ConstraintViolationException) e;
            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                map.put("data", ShiroResultEnum.FAIL.getCode());
                map.put("message", item.getMessage());
            }
            return map;
        }
        //其他异常统一处理
        map.put("data", ShiroResultEnum.FAIL.getCode());
        map.put("message", MessageEnum.FAIL.getMsg());
        return map;
    }

}